package com.sg.business.patch01.adminfunction;

import java.util.ArrayList;
import java.util.List;

import com.mobnut.admin.IFunctionExcutable;
import com.mobnut.db.DBActivator;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.sg.business.model.Document;
import com.sg.business.model.IModelConstants;

public class InitPLMDocument implements IFunctionExcutable {

	@Override
	public void run() {
		DBCollection docCol = getCol(IModelConstants.C_DOCUMENT);
		DBCursor dbCursor = docCol.find(new BasicDBObject().append(
				"IsSync",
				new BasicDBObject().append("$nin", new Object[] { Boolean.TRUE,
						Boolean.FALSE, null })));
		List<Object> trueIdList = new ArrayList<Object>();
		while (dbCursor.hasNext()) {
			DBObject dbo = dbCursor.next();
			Object _id = dbo.get("_id");
			Object IsSync = dbo.get("IsSync");
			Object plmid = dbo.get("plmid");
			if (IsSync.equals(plmid)) {
				trueIdList.add(_id);
			}
		}
		dbCursor.close();
		if (trueIdList.size() > 0) {
			docCol.update(
					new BasicDBObject().append("_id",
							new BasicDBObject().append("$in", trueIdList)),
					new BasicDBObject().append("$set",
							new BasicDBObject().append("IsSync", Boolean.TRUE)),
					false, true);
		}
		DBCursor dbCursor2 = docCol.find(new BasicDBObject()
				.append("acl", null));
		while (dbCursor2.hasNext()) {
			DBObject dbo = dbCursor2.next();
			Object folderid = dbo.get(Document.F_FOLDER_ID);
			Object _id = dbo.get("_id");
			DBObject dbObject = docCol.findOne(new BasicDBObject()
					.append(Document.F_FOLDER_ID, folderid)
					.append("_id", new BasicDBObject().append("$ne", _id))
					.append("acl", new BasicDBObject().append("$ne", null)));
			if (dbObject != null) {
				Object acl = dbObject.get("acl");
				docCol.update(
						new BasicDBObject().append("_id", _id),
						new BasicDBObject().append("$set",
								new BasicDBObject().append("acl", acl)), false,
						true);
			}
		}
		dbCursor2.close();
	}

	private DBCollection getCol(String collectionName) {
		return DBActivator.getCollection(IModelConstants.DB, collectionName);
	}

}
